package hu.bme.mit.rifl.business.base;

import hu.bme.mit.rifl.datamodel.Order;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;

public class RiflOrderInputQueue extends RiflOrderQueue {

	private MessageConsumer consumer;

	public RiflOrderInputQueue(String queueName) {
		super(queueName);
		try {
			consumer = getMessageConsumer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Gets a single order from the respective queue.
	 * 
	 * @return workitem of type hu.bme.mit.rifl.datamodel.Order
	 */
	public Order get() {
		try {
			ObjectMessage message = (ObjectMessage) consumer.receive(1000);

			if (message != null) {
				return (Order) message.getObject();
			} else
				return null;

		} catch (JMSException e) {
			// NOP
		}
		return null;
	}

	/**
	 * The close method must be overridden, since the connection should be
	 * closed after receiving the workitem.
	 */
	@Override
	public void close() {
		try {
			this.connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Creates a MessageConsumer.
	 * 
	 * @return The MessageConsumer instance which is able to recieve a workitem.
	 * @throws Exception
	 */
	public MessageConsumer getMessageConsumer() throws Exception {
		MessageConsumer messageConsumer = this.session
				.createConsumer(this.queue);
		this.connection.start();

		return messageConsumer;
	}
}
